<script lang="ts">
	import type { MemberInfo } from '$lib/api/proto/roadmap_member_api';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import { roadmapStore } from '../store.svelte';

	const PAGE_SIZE = 10;

	let curPage = $state(0);
	let memberList = $state([] as MemberInfo[]);
	let totalCount = $state(0);
	const pageCount = $derived(Math.ceil(totalCount / PAGE_SIZE));
	let curMember = $state(null as MemberInfo | null);

	async function loadMemberList() {
		if (userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.roadmapMemberApiClient.listMember({
				sessionId: userStore.userSession,
				roadmapId: roadmapStore.roadmapId,
				offset: curPage * PAGE_SIZE,
				limit: PAGE_SIZE
			}).response
		);
		memberList = res.memberList;
		totalCount = res.totalCount;
	}

	$effect(() => {
		loadMemberList();
	});
</script>

<div class="bg-base-200 rounded-box relative pb-[30px]">
	<h3 class="p-4 pb-2 text-2xl font-semibold">成员列表</h3>
	<ul class="list bg-base-200 shadow-none w-[200px] p-0 h-[30vh] overflow-y-auto">
		{#each memberList as member}
			<li class="list-row">
				<div
					role="none"
					class="w-[170px] p-2 rounded-box cursor-pointer {member.memberUserId ==
					curMember?.memberUserId
						? 'bg-base-300'
						: ''} hover:bg-base-300"
					onclick={() => {
						curMember = member;
						roadmapStore.loadNodeStateList(member.memberUserId);
					}}
				>
					{member.memberDisplayName}
				</div>
			</li>
		{/each}
	</ul>
	{#if pageCount > 1}
		<div class="join bg-base-200 absolute right-0">
			{#if curPage != 0}
				<button
					class="join-item btn btn-xs {curPage == 0 ? 'btn-active' : ''}"
					onclick={() => (curPage = 0)}>1</button
				>
			{/if}
			{#if pageCount > 3 && curPage > 1}
				<button class="join-item btn btn-xs btn-disabled">...</button>
			{/if}
			{#if curPage < pageCount}
				<button class="join-item btn btn-xs btn-active">{curPage + 1}</button>
			{/if}
			{#if curPage + 1 < pageCount}
				<button class="join-item btn btn-xs" onclick={() => (curPage += 1)}>{curPage + 2}</button>
			{/if}
			{#if pageCount - curPage > 4}
				<button class="join-item btn btn-xs btn-disabled">...</button>
			{/if}
			{#if pageCount - curPage > 3}
				<button class="join-item btn btn-xs" onclick={() => (curPage = pageCount - 2)}
					>{pageCount - 1}</button
				>
			{/if}
			{#if pageCount - curPage > 2}
				<button class="join-item btn btn-xs" onclick={() => (curPage = pageCount - 1)}
					>{pageCount}</button
				>
			{/if}
		</div>
	{/if}
</div>
